package com.woyao;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AlertDialog;
import android.telephony.TelephonyManager;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;

import com.woyao.core.model.BaseResponse;
import com.woyao.core.service.AccountService;
import com.woyao.core.util.Common;
import com.woyao.core.util.ServiceFactory;

import java.io.IOException;

import retrofit2.Call;

public class WelcomeActivity extends Activity {
    private TextView versionName;

    ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }


        setContentView(R.layout.activity_welcome);

        versionName = (TextView) findViewById(R.id.version_name);

        versionName.setText(Common.getCurrentVersion(WelcomeActivity.this));

        SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);
        Boolean agreed = shared.getBoolean("agreed", false);

        WoyaoooApplication.hasLogin = shared.getBoolean("logged", false);
        WoyaoooApplication.userId = shared.getInt("userId", 0);
        WoyaoooApplication.mobile = shared.getString("mobile", "");;
        WoyaoooApplication.displayname = shared.getString("displayname", "");;
        WoyaoooApplication.location = shared.getString("location", "");
        WoyaoooApplication.title = shared.getString("title", "");
        WoyaoooApplication.snailview = shared.getString("snailview", "");
        WoyaoooApplication.demand_id = shared.getInt("demand_id", 0);
        WoyaoooApplication.member_id = shared.getInt("member_id", 0);
        WoyaoooApplication.message_num = shared.getInt("message_num", 0);



        if (!agreed) {
            showPrivacyDialog(WelcomeActivity.this);
        }else{
            handleNext();
        }

    }

    private void tryGetImei(){
         if (  ActivityCompat.checkSelfPermission(WelcomeActivity.this,Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED){
             ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);
         }else{
             getDeviceID();
         }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1: {    // 1 for location
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    getDeviceID();

                } else {
//                    Log.i("woyaooo", "onRequestPermissionsResult:  fail");
//                    Dialog alertDialog = new AlertDialog.Builder(RegisterActivity.this).
//                            setTitle("信息").
//                            setMessage("为稳定匹配合作，请授权访问定位").
//                            setIcon(R.drawable.ic_launcher).
//                            setPositiveButton("确定", new DialogInterface.OnClickListener() {
//
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                }
//                            }).
//                            create();
//                    alertDialog.show();
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                }
                return;
            }
            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private String getDeviceID(){
        String ret = "";
        try {
            TelephonyManager tm = (TelephonyManager) getSystemService(Activity.TELEPHONY_SERVICE);
            if (tm != null){
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    ret = tm.getImei();
                }else{
                    ret = tm.getDeviceId();
                }
            }
        }catch(SecurityException se){

        }
        ret = Settings.System.getString(getContentResolver(), Settings.System.ANDROID_ID);

        if (ret == null){
            ret = "";
        }
        return ret;
    }

    private void showPrivacyDialog(final Context context) {

        String title ="用户协议和隐私条款提示";
        String btnYes="同意";
        //弹框内容---------富文本显示
        String dialogContent="请您务必仔细阅读并透彻理解《用户协议》和《隐私政策》，在使用我要合作网过程中，我们访问您的各项权限是为了向您提供服务、优化您的服务以及保障您的账号安全";
        SpannableStringBuilder dialogContentStyle = new SpannableStringBuilder(dialogContent);//需要用富文本显示的内容

        int startIndex1=dialogContent.indexOf("《用") ;
        int contentLength1="《用户协议》".length();

        dialogContentStyle.setSpan(new ForegroundColorSpan(Color.parseColor("#62839A")),startIndex1,startIndex1+contentLength1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        dialogContentStyle.setSpan(new textClickProtocol(),startIndex1,startIndex1+contentLength1, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        int startIndex=dialogContent.indexOf("《隐") ;
        int contentLength="《隐私政策》".length();

        dialogContentStyle.setSpan(new ForegroundColorSpan(Color.parseColor("#62839A")),startIndex,startIndex+contentLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        dialogContentStyle.setSpan(new textClickPrivacy(),startIndex,startIndex+contentLength, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        //取消按钮-----------富文本显示
        String dialogCancel ="拒绝";
        int dialogCancelEnd=dialogCancel.length();
        SpannableStringBuilder dialogCancelStyle = new SpannableStringBuilder(dialogCancel);
        dialogCancelStyle.setSpan(new ForegroundColorSpan(Color.parseColor("#62839A")),0,dialogCancelEnd, Spannable.SPAN_INCLUSIVE_INCLUSIVE);

        final PrivacyDialog privacyDialog = new PrivacyDialog(context, title, dialogContentStyle, btnYes, dialogCancelStyle);
        privacyDialog.show();
        privacyDialog.setCancelable(false);//点击返回键或者空白处不消失
        privacyDialog.setClickListener(new PrivacyDialog.ClickInterface() {
            @Override
            public void doCofirm() {
                privacyDialog.dismiss();
                SharedPreferences shared = getSharedPreferences("login", MODE_PRIVATE);

                SharedPreferences.Editor editor = shared.edit();
                editor.putBoolean("agreed", true);

                editor.commit();

                getUserId();


            }
            @Override
            public void doCancel() {
                privacyDialog.dismiss();
                finish();
            }
        });
    }

    /**
     * 用户协议及弹框富文本的点击事件
     */
    private class textClickPrivacy  extends ClickableSpan {
        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#62839A"));
        }

        @Override
        public void onClick(@NonNull View widget) {
            Intent intent = new Intent();
            intent.setClass(WelcomeActivity.this, WebviewActivity.class);
            intent.putExtra("title", "隐私政策");
            intent.putExtra("link", "https://www.woyaooo.com/privacy.html");
            startActivity(intent);
        }
    }

    private class textClickProtocol  extends ClickableSpan {
        @Override
        public void updateDrawState(@NonNull TextPaint ds) {
            ds.setUnderlineText(false);
            ds.setColor(Color.parseColor("#62839A"));
        }

        @Override
        public void onClick(@NonNull View widget) {
            Intent intent = new Intent();
            intent.setClass(WelcomeActivity.this, WebviewActivity.class);
            intent.putExtra("title", "用户协议");
            intent.putExtra("link", "https://www.woyaooo.com/protocol.html");
            startActivity(intent);
        }
    }
    private  void handleNext(){

        new Handler().postDelayed(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub

                    Intent intent  = new Intent(WelcomeActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();

            }
        }, 1000);
    }




    private void getUserId(){
        final String version =  "" + Common.getCurrentVersion(WelcomeActivity.this);
        final String device = Common.getDeviceID( WelcomeActivity.this) ;
        AsyncTask<Void,Void,BaseResponse> loadTask =
                new AsyncTask<Void, Void, BaseResponse>() {
                    @Override
                    protected BaseResponse doInBackground(Void... params) {
                        AccountService svc = ServiceFactory.get(AccountService.class);
                        Call<BaseResponse> responseCall = svc.getUserId(device,"android",version);
                        try {
                            BaseResponse response = responseCall.execute().body();
                            return response;
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                    @Override
                    protected void onPostExecute(final BaseResponse response) {

                        if(response != null && response.isSuccess() ){
                            SharedPreferences shared = getApplication().getSharedPreferences("login", MODE_PRIVATE);
                            SharedPreferences.Editor editor = shared.edit();
                            editor.putBoolean("logged", false);
                            WoyaoooApplication.key = response.getCondition();
                            WoyaoooApplication.userId = Integer.parseInt(response.getMessage());
                            editor.putString("key",WoyaoooApplication.key   );
                            editor.putInt("userId",WoyaoooApplication.userId   );
                            editor.commit();
                            handleNext();
                        }else{
                            Dialog alertDialog = new AlertDialog.Builder(WelcomeActivity.this).
                                    setTitle("信息").
                                    setMessage("请检查网络情况").
                                    setIcon(R.drawable.ic_launcher).
                                    setPositiveButton("确定", new DialogInterface.OnClickListener() {

                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }).
                                    create();
                            alertDialog.show();
                        }

                    }
                };
        loadTask.execute((Void)null);
    }




    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    }

}
